package xyz.hubery.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    @Value("${no.require.uris:/admin/login,/user/gt/register,/user/login,/user/sms/sendTo,/user/users/setPassword,/user/users/register,/admin/webConfigs/banners,/admin/notices/simple,/admin/notices/simple/**,/exchange/markets/kline/**}")
    private Set<String> noRequireTokenUris; // 存放不需要认证的uri列表
    private final AntPathMatcher pathMatcher = new AntPathMatcher();
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 用户请求到达前处理
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1、搜先判断该请求是否需要认证
        if(!isRequireToken(exchange)) {
            return chain.filter(exchange); //不需要认证，直接放行
        }
        // 2、获取用户Token
        String token = getUserToken(exchange);
        // 3、判断Token是否有效
        if(!StringUtils.isEmpty(token) && isValidToken(token)) {
           return chain.filter(exchange); //token 有效，直接放行
        }
        return buildNoAuthorizationError(exchange);
    }

    private Mono<Void> buildNoAuthorizationError(ServerWebExchange exchange ){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().set("Content-Type", "application/json;charset=UTF-8");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg","Token is null or Error");
        DataBuffer dataBuffer =
                response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(dataBuffer));
    }

    private boolean isValidToken(String token) {
        Boolean hasKey = redisTemplate.hasKey(token);
        return hasKey;
    }

    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer ","");
    }

    private boolean isRequireToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();

        for (String pattern : noRequireTokenUris) {
            if (pathMatcher.match(pattern, path)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
